package com.mce.nebula.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 验证码服务
 * 对应Python的验证码功能
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CaptchaService {
    
    // 存储验证码的临时缓存（实际项目中应该使用Redis）
    private final Map<String, CaptchaInfo> captchaCache = new ConcurrentHashMap<>();
    
    // 验证码有效期（5分钟）
    private static final long CAPTCHA_EXPIRE_TIME = 5 * 60 * 1000;
    
    /**
     * 生成验证码
     */
    public String generateCaptcha(String sessionId) {
        // 生成4位数字验证码
        String captcha = String.format("%04d", ThreadLocalRandom.current().nextInt(1000, 10000));
        
        CaptchaInfo captchaInfo = new CaptchaInfo(captcha, System.currentTimeMillis());
        captchaCache.put(sessionId, captchaInfo);
        
        log.debug("生成验证码: {} for session: {}", captcha, sessionId);
        return captcha;
    }
    
    /**
     * 验证验证码
     */
    public boolean validateCaptcha(String sessionId, String inputCaptcha) {
        if (sessionId == null || inputCaptcha == null) {
            return false;
        }
        
        CaptchaInfo captchaInfo = captchaCache.get(sessionId);
        if (captchaInfo == null) {
            log.warn("验证码不存在或已过期: {}", sessionId);
            return false;
        }
        
        // 检查是否过期
        if (System.currentTimeMillis() - captchaInfo.getCreateTime() > CAPTCHA_EXPIRE_TIME) {
            captchaCache.remove(sessionId);
            log.warn("验证码已过期: {}", sessionId);
            return false;
        }
        
        // 验证码验证（不区分大小写）
        boolean isValid = captchaInfo.getCaptcha().equalsIgnoreCase(inputCaptcha);
        
        // 验证后删除验证码（一次性使用）
        if (isValid) {
            captchaCache.remove(sessionId);
            log.debug("验证码验证成功: {}", sessionId);
        } else {
            log.warn("验证码验证失败: {} (输入: {}, 正确: {})", sessionId, inputCaptcha, captchaInfo.getCaptcha());
        }
        
        return isValid;
    }
    
    /**
     * 清理过期的验证码
     */
    public void cleanExpiredCaptchas() {
        long currentTime = System.currentTimeMillis();
        captchaCache.entrySet().removeIf(entry -> 
            currentTime - entry.getValue().getCreateTime() > CAPTCHA_EXPIRE_TIME);
    }
    
    /**
     * 验证码信息类
     */
    private static class CaptchaInfo {
        private final String captcha;
        private final long createTime;
        
        public CaptchaInfo(String captcha, long createTime) {
            this.captcha = captcha;
            this.createTime = createTime;
        }
        
        public String getCaptcha() { return captcha; }
        public long getCreateTime() { return createTime; }
    }
}
